package Meter::Action::AppartmentInfo;

#===============================================================================
#     REVISION:  $Id: AppartmentInfo.pm 88 2011-07-18 11:04:27Z xdr.box@gmail.com $
#  DESCRIPTION:  Show or update appartment info
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 88 $) [1];

use English qw( -no_match_vars );

#use Smart::Comments;

use Meter::Log;

use base qw(Meter::Action);

use Meter::Houses;

sub generate_page_content {
    my $self = shift;

    if ( $ENV{'REQUEST_METHOD'} eq 'GET' ) {
        return $self->_show_appartment_info();
    }
    else {
        return $self->_update_appartment_info();
    }
}

sub _show_appartment_info {
    my $self = shift;

    my $logger     = get_logger();
    my $appartment = $self->{'user'}->appartment();

    if ($appartment) {
        $logger->info( 'Showing appartment info of user '
                . $self->{'user'}->username() );
    }
    else {
        $logger->warn( 'User '
                . $self->{'user'}->username()
                . ' has not set appartment info yet' );
    }

    return $self->process_template(
        'appartment_info.tt2',
        {   username => $self->{'user'}->username(),
            houses   => [ Meter::Houses->retrieve_all() ],
            $appartment
            ? ( house_id          => $appartment->house()->house(),
                appartment_number => $appartment->appartment_number(),
                last_name         => $appartment->last_name(),
                first_name        => $appartment->first_name(),
                middle_name       => $appartment->middle_name(),
                cold_water_meter_number =>
                    $appartment->cold_water_meter_number(),
                hot_water_meter_number =>
                    $appartment->hot_water_meter_number(),
                )
            : (),
        }
    );
}

sub _update_appartment_info {
    my $self = shift;

    my $logger = get_logger();

    my $house = Meter::Houses->retrieve( $self->{'params'}{'house_id'} );

    if ( !$house ) {
        $logger->error(
            "User passed invalid house_id: '$self->{'params'}{'house_id'}'");

        return $self->redirect_error(
            'Ошибка сохранения данных: дом не найден',
            'appartment_info'
        );
    }

    eval {
        my $appartment = $self->{'user'}->appartment();

        if ( !$appartment ) {    # create new

            $appartment = Meter::Appartments->insert(
                {   user     => $self->{'user'},
                    house_id => $house->house(),
                    appartment_number =>
                        $self->{'params'}{'appartment_number'},
                    last_name   => $self->{'params'}{'last_name'},
                    first_name  => $self->{'params'}{'first_name'},
                    middle_name => $self->{'params'}{'middle_name'},
                    cold_water_meter_number =>
                        $self->{'params'}{'cold_water_meter_number'},
                    hot_water_meter_number =>
                        $self->{'params'}{'hot_water_meter_number'},
                }
            );
        }
        else {    # update existing

            $appartment->house( $house->house() );
            $appartment->appartment_number(
                $self->{'params'}{'appartment_number'} );
            $appartment->last_name( $self->{'params'}{'last_name'} );
            $appartment->first_name( $self->{'params'}{'first_name'} );
            $appartment->middle_name( $self->{'params'}{'middle_name'} );
            $appartment->cold_water_meter_number(
                $self->{'params'}{'cold_water_meter_number'} );
            $appartment->hot_water_meter_number(
                $self->{'params'}{'hot_water_meter_number'} );

            $appartment->update();
        }
    };

    if ($EVAL_ERROR) {
        my $why = $EVAL_ERROR;
        $logger->error("Cannot set appartment info: $why");

        return $self->redirect_error(
            'Ошибка сохранения данных',
            'appartment_info', $why );
    }

    return $self->redirect_ok(
        'Информация успешно сохранена',
        'appartment_info' );
}

sub get_error_regexes_list {
    my $self = shift;

    return [
        {   regex =>
                qr/\Qcolumns house_id, appartment_number are not unique\E/xms,
            message =>
                'квартира в этом доме и с таким номером уже зарегистрирована в системе',
        },

        {   regex => qr/\Qcolumn cold_water_meter_number is not unique\E/xms,
            message =>
                'счётчик ХВ с таким номером уже зарегистрирован в системе',
        },

        {   regex => qr/\Qcolumn hot_water_meter_number is not unique\E/xms,
            message =>
                'счётчик ГВ с таким номером уже зарегистрирован в системе',
        },

        {   regex => qr/\Qappartment_number fails 'regexp' constraint\E/xms,
            message =>
                'номер квартиры не соответствует установленному формату',
        },

        {   regex => qr/\Qlast_name fails 'regexp' constraint with ''\E/xms,
            message =>
                'фамилия собственника не указана',
        },

        {   regex => qr/\Qfirst_name fails 'regexp' constraint with ''\E/xms,
            message => 'имя собственника не указано',
        },

        {   regex =>
                qr/\Qcold_water_meter_number fails 'regexp' constraint\E/xms,
            message =>
                'номер счётчика ХВ не соответствует установленному формату',
        },

        {   regex =>
                qr/\Qhot_water_meter_number fails 'regexp' constraint\E/xms,
            message =>
                'номер счётчика ГВ не соответствует установленному формату',
        },

        {   regex   => qr/\QXXX\E/xms,
            message => 'YYY',
        },
    ];
}

1;
